package com.zjz.demo.PC;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2021/10/08/13:11
 * @Description: 一个加1,一个减  通知,等待,唤醒  -- 生产者通知有货了,等待,唤醒   消费者通知没货了,等待,唤醒
 * @Target: 生产者,没有了就生产东西.
 */
public class Product {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }

}

// 判断等待,业务,通知
class Data{  // 数字,资源类
    private int num = 0;
    // +1
    public synchronized void increment() throws InterruptedException {
        while(num!=0){
            // 等待
            this.wait();
            // 业务
            System.out.println(Thread.currentThread().getName()+"==>"+num);
        }
        num++;
        // 通知其它线程
        this.notify();
    }
    // -1

    public synchronized void decrement() throws InterruptedException {
        while (num==0){
         // 等待
         this.wait();
         // 业务
            System.out.println(Thread.currentThread().getName()+"==>"+num);
        }
        num--;

        // 通知
        this.notify();

    }


}
